<?php
namespace app\wxpro\controller;
use think\Db;
use think\Controller;
use app\service\orderService;
use app\service\chargeRuleService;
use app\service\wechatService;
class Package extends Controller{
	
	public function packageCarList(){
		$openid=request()->get("openid");
		$carlist=Db::table("car_wx_bind")
					->alias('a')
					->join('package b','a.car_number=b.car_number')
					->where('a.openid',$openid)
					->select();
		if(empty($carlist)){
			$arr["status"]="0";
			$arr["error"]="您尚未办理月卡，请到停车场办理月卡";
			return json_encode($arr);
		}else{
			//查询停车场信息
			
			$arr["status"]="1";
			$arr["carlist"]=$carlist;
			return json_encode($arr);
		}				
	}
	
	//微信创建订单唤起收银台
	public function wxpay(){
		$openid=request()->get("openid");
		//月租车记录id
		$id=request()->get("id");
		$packageinfo=Db::table("package")->where("id",$id)->find();
		if(empty($packageinfo)){
			return json(['info' => "请重新查询月租车辆信息"]);
		}
		//查询停车场信息
		$parkinglot=Db::table("parkinglotinfo")->where("out_parking_id",$packageinfo["out_parking_id"])->find();
		
		$packageOrder["out_order_no"]=date('YmdHis').rand(10000,999999);
		$packageOrder["ordermoney"]=$packageinfo["price"]*$parkinglot["car_renewal_period"];
		$packageOrder["user_id"]=$openid;
		$packageOrder["car_number"]=$packageinfo["car_number"];
		$packageOrder["out_parking_id"]=$packageinfo["out_parking_id"];
		$packageOrder["parking_name"]=$parkinglot['parking_name'];
		
		
		//根据停车场查询商户信息
		$propertyinfo = (new orderService())->propertyInfo($parkinglot['parking_id']);
		//生成订单
		$data['appid'] = 'wx352362f198d9c56b';//公众账号ID
        $data['mch_id'] = '1484539292';//商户号
        $data['sub_appid'] = 'wx6e64e3c7372be385';//小程序id 
		//$data['sub_mch_id'] = (new orderService())->subMchId($orderIdInfo['parking_id']);//子商户公众账号ID
		$data['sub_mch_id']="1500219082";
		$data['nonce_str'] = (new wechatService())->createNoncestr();;//随机字符串
		$data['body'] = $parkinglot["parking_name"].'月租车续费';//商品描述
		$data['out_trade_no'] = $packageOrder["out_order_no"];//商户订单号
		$data['total_fee'] = $packageOrder["ordermoney"]*100;//总金额
		$data['spbill_create_ip'] = $_SERVER["REMOTE_ADDR"];//终端IP
		$data['notify_url'] = 'https://www.huiwang1688.com/wxpro/Package/wxnotice';//通知url
		$data['trade_type'] = 'JSAPI';
		$data['sub_openid'] = $openid;//用户标识
		//$wxkey = $propertyinfo['wx_key'];//key
		$wxkey="asdfaASDFASDFASFasfsadf6546A84SA";
		$data['sign'] = (new wechatService())->MakeSign($data,$wxkey);//签名
		// return json(['info' => $data]);
		//输出xml字符
		$xml = (new wechatService())->ToXml($data);
		$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
		
		$payInfo = (new wechatService())->post_curl_data($url,$xml);
		
		$payInfo = json_decode(json_encode(simplexml_load_string($payInfo, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		//var_dump($payInfo);die;
		if($payInfo['return_code'] !== 'SUCCESS'){
			return json(['info' => $payInfo]);
			return json(['info' => $payInfo['return_msg']]);
		}else{
			$packageOrder['price']=$packageinfo["price"];
			$packageOrder['car_renewal_period']=$parkinglot["car_renewal_period"];
			$packageOrder['order_time'] = date('Y-m-d H:i:s',time());
			$packageOrder['status'] = 1;
			$packageOrder['pay_type']=2;
			$packageOrderAdd = Db::table("package_order")->insert($packageOrder);
			
			//返回结果到前台唤起收银台
			if($packageOrderAdd){
				$jsApiParameters['appId'] = $payInfo['sub_appid'];
				$jsApiParameters['timeStamp'] = time();
				$jsApiParameters['timeStamp'] = '$jsApiParameters["timeStamp"]';
				
				$jsApiParameters['nonceStr'] = (new wechatService())->createNoncestr();
				$jsApiParameters['package'] = 'prepay_id='.$payInfo['prepay_id'];
				$jsApiParameters['signType'] = 'MD5';
			
				$jsApiParameters['paySign'] =(new wechatService())->MakeSigns($jsApiParameters,$wxkey);
				$jsApiParameters['trade_no']=$payInfo['prepay_id'];
				$wxpro_form["ctime"]=time();
				$wxpro_form["openid"]=$openid;
				$wxpro_form["form_id"]=$payInfo['prepay_id'];
				$wxpro_form["num"]=4;
				$res=Db::table("wxpro_form")->insert($wxpro_form);
				
				return json_encode($jsApiParameters); 
				
			}else{
				return json(['info' => '订单存储失败']);
			}
		}
	}
	
	
	public function wxnotice(){
		$address = 'C:\phpStudy\PHPTutorial\WWW\huiwang1688\public\notice\wxnotice\\'.'package'.date('YmdHis').rand(100000,999999).'.txt';//文本路径
        file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);//将数据读入文本
		
		$xmldata = file_get_contents($address);
        //将xml数据转化为数组
        $notice = json_decode(json_encode(simplexml_load_string($xmldata, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
       
		if(isset($notice)){
            if($notice['return_code'] == 'SUCCESS' && $notice['result_code'] == 'SUCCESS'){
				 //根据支付宝交易号查询月租车账单信息
                $packageOrder = Db::table("package_order")->where("out_order_no",$notice['out_trade_no'])->find();
				//var_dump($packageOrder);die;
				if($packageOrder["status"]!="2"){
					//根据车牌号和停车场id查询月租车到期时间
					$carpackage=Db::table("package")->where("out_parking_id",$packageOrder["out_parking_id"])->where("car_number",$packageOrder["car_number"])->find();
					$data["id"]=$packageOrder["id"];
					$data["status"]="2";//更改订单状态为已支付
					$data["order_no"]=$notice["transaction_id"];
					$data["pay_time"]=date('Y-m-d H:i:s');
					$data["beforeEndtime"]=$carpackage["out_time"];
					
					if(strtotime($carpackage["out_time"])<time()){
						//如果月租车已到期,则从当前时间加一个月
						$data["afterEndtime"]=date("Y-m-d H:i:s",strtotime("+".$packageOrder["car_renewal_period"]." month",strtotime($data["pay_time"])));
					}else{
						//如果月租车未到齐到期,则从到期时间加一个月
						$data["afterEndtime"]=date("Y-m-d H:i:s",strtotime("+".$packageOrder["car_renewal_period"]." month",strtotime($carpackage["out_time"])));
					}
					
					$res=Db::table("package_order")->update($data);
					if($res){
						Db::table("package")->update(["id"=>$carpackage["id"],"out_time"=>$data["afterEndtime"],"status"=>"1"]);
					}
				}
			}
		}
	}
	
	
   
    
    
}